package com.typing.battle.view;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.typing.battle.R;
import com.typing.battle.activity.TypingBattleChatRoomActivity;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.ServerPollingReceiver;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;

public class ChatRoomListView  extends ListView implements OnItemClickListener ,OnDataSyncCompleteListener{

	private Context mContext;
	private Activity mActivity;
	public JSONArray list = new JSONArray();
	
	private ChatRoomListAdapter adapter;

	private LinearLayout layout;
	public TextView chatRoomId;
	public TextView chatRoomName;
	public TextView chatRoomPeople;
	private LayoutInflater inflate;
	
	private PreferenceMgr mgr;
	private int rowCount = 15;
	private int currentIndex = 0;
	private int totalCount;
	private String searchText;
	public ChatRoomListView(Context context) {
		super(context);
		mContext = context;
		mActivity = (Activity)context;
		inflate = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		adapter = new ChatRoomListAdapter();
//		getChatRoomList();
		setAdapter(adapter);
		setOnItemClickListener(this);
		mgr = PreferenceMgr.getInstance(context);
	}
	public void searchChatRoom(String str){
		searchText = str;
		if(adapter != null){
			currentIndex = 0;
			list = new JSONArray();
			getChatRoomList();
			adapter.notifyDataSetChanged();
		}
	}
	public void getChatRoomList(){
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_SELECT);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		if(searchText != null && !searchText.trim().equals("")){
			dto.setChatRoomName(searchText);
		}
		dto.setStartIndex(currentIndex);
		dto.setEndIndex(currentIndex + rowCount);
		try{
			ServerComunicationUtil.serverAction(dto,mContext,this);
		}catch(Exception e){
			Log.e("", "TYPE_CHAT_ROOM_SELECT ERROR ::: "+e.getMessage());
			e.printStackTrace();
		}
	}
	public void refreshData(){	
		currentIndex = 0;
		list = new JSONArray();
		getChatRoomList();
		
		adapter.notifyDataSetChanged();
	}
	public void getNextList(){
		getChatRoomList();
		adapter.notifyDataSetChanged();
	}
	public class ChatRoomListAdapter extends BaseAdapter{
		
		@Override
		public int getCount() {
			return list == null ? 0 : list.length();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if(convertView ==null){
				layout  = (LinearLayout)inflate.inflate(R.layout.chat_room_list_row, null);
			}else{
				layout =(LinearLayout)convertView;	
			}
			chatRoomId = (TextView)layout.findViewById(R.id.chat_room_id);
			chatRoomName = (TextView)layout.findViewById(R.id.chat_room_name);
			chatRoomPeople = (TextView)layout.findViewById(R.id.chat_room_people);
			
			try{
				JSONObject data = new JSONObject(list.get(position).toString());
				//chatRoomId.setText(data.get("chatRoomId").toString());
				String roomType ="2".equals(data.get("chatRoomType").toString())?"[비밀] ":"[일반] ";
				chatRoomId.setText(""+(position+1));
				chatRoomName.setText(roomType+data.get("chatRoomName").toString());
				chatRoomPeople.setText(data.get("maxPeopleCount").toString());
			}catch(Exception e){
				
			}
			
			return layout;
		}
		
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		try{
			JSONObject data = new JSONObject(list.get(position).toString());
//			Intent intent = new Intent(mContext,TypingBattleChatRoomActivity.class);
//			intent.putExtra("CHAT_ROOM_ID", data.get("chatRoomId").toString());
			if("2".equals(data.get("chatRoomType").toString())){
				//이곳에 비번 입력받는 얼럿을 띄워라 그리고 dto 에 setChatRoomPwd 로 넣어라
			}
			ServerComunicationDTO dto = new ServerComunicationDTO();
			dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN);
			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
			dto.setSendType(ServerPollingReceiver.TYPE_ROOM_IN);
			dto.setChatRoomId(data.get("chatRoomId").toString());
			ServerComunicationUtil.serverAction(dto,mContext,this);
			//mActivity.finish();
		}catch(Exception e){
			Log.e("", "TYPE_CHAT_ROOM_JOIN ERROR ::: "+e.getMessage());
			e.printStackTrace();
		}		
	}
	public int getTotalCount(){
		return this.totalCount;
	}
	public int getCurrentIndex(){
		return this.currentIndex;
	}
	@Override
	public void onSyncComplete(int resultCode) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, mContext);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN){
				Intent intent = new Intent(mContext,TypingBattleChatRoomActivity.class);
				intent.putExtra("CHAT_ROOM_ID", dto.getChatRoomId());
				String result = (String)resultObj;
				if("OK".equals(result)){
					mContext.startActivity(intent);
				}else if("FULL".equals(result)){
					Toast toast = Toast.makeText(mContext, "채팅방 정원이 다 찼습니다.",
							Toast.LENGTH_SHORT);
					toast.show();
				}else if("WRONG_PASSWORD".equals(result)){
					Toast toast = Toast.makeText(mContext, "비밀번호가 틀렸습니다.",
							Toast.LENGTH_SHORT);
					toast.show();
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_SELECT)	{
				try{
					JSONObject resultObject = new JSONObject((String)resultObj);
					JSONArray resultArray = new JSONArray(resultObject.get("list").toString());
					Log.d("", "onSyncComplete===>>>"+resultObject.toString());
					//list 초기화.
					if(resultArray!=null && resultArray.length()>0)	list = new JSONArray();
					for(int i = 0 ; i < resultArray.length(); i++){
						list.put(resultArray.get(i)); 
					}
					totalCount = resultObject.getInt("totalCount");
					currentIndex = currentIndex + rowCount;
					
					if(list==null || list.length()<1){
						((View)this.getParent()).setVisibility(GONE);
					}else{
						((View)this.getParent()).setVisibility(VISIBLE);
					}
					adapter.notifyDataSetChanged();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
//		super.onSyncComplete(resultCode, dto, resultObj);
	}
}
